/*
 * @Author: wurangkun wurangkun@qq.com
 * @Date: 2023-04-04 14:30:01
 * @LastEditors: wurangkun wurangkun@qq.com
 * @LastEditTime: 2023-06-19 11:13:17
 * @FilePath: \ts-koa-starter-master\src\service\file.ts
 * @Description: 文件上传下载 写入
 */
import { saveFile } from "src/utils/file/upload";
import type { UploadOption } from "../typings/file";
import { send, setCreateTime } from "src/utils/tools";
import { sendCode } from "enums/send";
const { file_upload } = require("../models/file/file_upload")

const fs = require('fs');
export default class FileService {
  list = async (data) => {
    try {
      const { countPerPage = 10, currentPage = 1 } = data
      const res = await file_upload.findAll({
        order: [
          ['create_time', 'DESC']
        ],
        where: {
          categoryid: data.categoryid
        },
        limit: +countPerPage, // 每页多少条
        offset: +(countPerPage * (currentPage - 1)) // 跳过多少条
      })
      return send({ data: res });
    } catch (error) {
      console.log(error);
      return send({ msg: '服务错误', code: sendCode.失败 });
    }
  }
  /**
   * 上传
   */
  upload = (data: UploadOption) => {
    try {
      saveFile(data, (option: { path: string }) => {
        const { path } = option;
        // @ts-ignore
        const { originalFilename, size } = data.files
        file_upload.bulkCreate([{
          type: data.type,
          path,
          filename: originalFilename,
          description: data.description || '暂无描述',
          size,
          downloadTimes: 0,
          categoryid: +data.categoryid,
          create_time: setCreateTime()
        }]).catch((err) => {
          console.log(err.message);
        })
      });
      return send()
    } catch (error) {
      return send({ msg: '服务错误', code: sendCode.失败 });
    }
  };
  /**
   * 下载
   */
  download = async (ctx) => {
    const { id } = ctx.mydata
    try {
      const { path, filename, size, downloadTimes } = await findFile(id)
      // 创建一个可读流
      const stream = fs.createReadStream(path);
      // 设置响应头
      ctx.attachment(filename);
      ctx.type = 'application/octet-stream';
      file_upload.update({
        downloadTimes: downloadTimes + 1
      }, {
        where: {
          id
        }
      })
      return stream
    } catch (error) {
      // 检查文件是否存在
      return send({ msg: '文件不存在', code: sendCode.失败 });
    }

    // 写入响应数据
  };
  /**
   * 删除文件
   */
  delete = async (data: { id: number }) => {
    try {
      const { path, filename, size } = await findFile(data.id)
      await deleteFile(path)
      await file_upload.destroy({
        where: {
          id: data.id
        }
      })
      return send({ msg: "删除成功" });
    } catch (error) {
      console.log(error);
      return send({ msg: '服务错误', code: sendCode.失败 });
    }
  };
}


const findFile = async (id: number) => {
  const res: UploadOption = await file_upload.findOne({
    where: {
      id
    },
  })
  return res
}
// 删除文件
const deleteFile = (filePath): Promise<void> => {
  return new Promise((resolve, reject) => {
    fs.unlink(filePath, (error) => {
      if (error) {
        reject(error);
      } else {
        resolve();
      }
    });
  });
};